package com.example.im.ui.fragment

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.im.common.Enumerate
import com.example.im.R
import com.example.im.bean.UserRoom
import com.example.im.bean.EventBusData
import com.example.im.common.Constants
import com.example.im.mvp.base.BasePresenter
import com.example.im.ui.abstracts.AbstractBaseFragment
import com.example.im.ui.activity.UserActivity
import com.example.im.db.DatabaseStorage
import com.example.im.ui.adapter.UserRoomAdapter
import com.example.im.utils.JsonUtils
import com.example.im.utils.LogUtils
import kotlinx.android.synthetic.main.fragment_friend_view_page.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class FriendUserFragment : AbstractBaseFragment<BasePresenter<*>>(),
    UserRoomAdapter.OnClickItemListener {

    var users = mutableListOf<UserRoom>()
    var adapter: UserRoomAdapter? = null

    init {
        val userRooms = DatabaseStorage.getUserRoomToUser()
            ?: arrayListOf()
        users.addAll(userRooms)
    }


    override val layoutId: Int
        get() = R.layout.fragment_friend_view_page

    override fun initView() {

        EventBus.getDefault().register(this)

        adapter = UserRoomAdapter(activity!!, users)
        adapter!!.setOnItemClickListener(this)
        recycler_view.layoutManager = LinearLayoutManager(activity)
        recycler_view.adapter = adapter

    }

    override fun initPresenter() {

    }

    override fun initLazyLoad() {

    }

    override fun onDestroyView() {
        super.onDestroyView()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventMainThread(eventBus: EventBusData<MutableList<UserRoom>>) {
        if (eventBus.type ?: return != Enumerate.Handle.list_friend)
            return
        adapter?.addDataAll(eventBus.data ?: return)
//        when (eventBus.action ?: return) {
//            Enumerate.Action.list_add ->
//                adapter!!.addDataAll(eventBus.data ?:return)
//            Enumerate.Action.list_delete ->
//                adapter!!.removeDataItem(eventBus.data ?: return)
//            else -> return
//        }
    }

    override fun onClickItem(view: View, position: Int) {
        val intent = Intent(activity, UserActivity::class.java)
        intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_POINT, Constants.BUNDLE_T0_USER_POINT_1)
        intent.putExtra(Constants.BUNDLE_T0_USER_ROOM_DATA, users[position])
        activity!!.startActivity(intent)
    }
}